import * as THREE from 'three';
const model = new THREE.Group();
const loader = new THREE.FileLoader();
loader.setResponseType("json")
loader.load('/china.json',(data)=>{
    const lineGroup = new THREE.Group();
    const meshGroup = new THREE.Group();
    const cityPointGroup = new THREE.Group();
    data.features.forEach((area)=>{
        // coordinates数据分为单组和多组，将单组的封装为多组
        if(area.geometry.type === 'Polygon'){
            area.geometry.coordinates = [area.geometry.coordinates]
        }
        lineGroup.add(moreLine(area.geometry.coordinates)) 
        meshGroup.add(shapeMesh(area.geometry.coordinates))
        cityPointGroup.add(cityPointMesh(1.2,area.properties.cp[0],area.properties.cp[1]))
    })
    lineGroup.position.z += 1 + 0.1
    cityPointGroup.position.z += 1 + 0.1
    model.add(lineGroup,meshGroup,cityPointGroup)
    console.log('model',model);
})

// 批量产生轮廓线
const moreLine = (coordinates)=>{
    const groupLine = new THREE.Group();
    coordinates.forEach(polygon => {
        var pointArr = []
        polygon[0].forEach((elem)=>{
            pointArr.push(elem[0],elem[1],0)
        })
        groupLine.add(oneLine(pointArr))
    });
    return groupLine
}
// 产生一条轮廓线
const oneLine = (pointArr)=>{
    const geometry = new THREE.BufferGeometry();
    const vertices = new Float32Array(pointArr);
    geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
    const material = new THREE.LineBasicMaterial({
        color: 0x00ffff
    });
    const line = new THREE.LineLoop(geometry,material);
    return line;
}
// 产生多边形面
const shapeMesh = (coordinates)=>{
    const groupMesh = new THREE.Group();
    coordinates.forEach(polygon => {
        var pointArr = []
        polygon[0].forEach((elem)=>{
            pointArr.push(new THREE.Vector3(elem[0],elem[1],0))
        })
        var material = new THREE.MeshLambertMaterial({
            color: 0x004444,
            side: THREE.DoubleSide, //两面可见
        }); //材质对象
        const heartShape = new THREE.Shape(pointArr);
        const geometry = new THREE.ExtrudeGeometry( heartShape ,{
            depth: 1, //拉伸长度
            bevelEnabled: false //无倒角
        });
        groupMesh.add(new THREE.Mesh( geometry, material ) )
    });
    return groupMesh
}
// 矩形平面网格模型设置背景透明的png贴图
const cityPointMesh = (size,x,y)=>{
    const geometry = new THREE.PlaneGeometry( 1, 1 );
    const texture = new THREE.TextureLoader().load( "/贴图.png" );
    const material = new THREE.MeshBasicMaterial({
        map:texture,
        transparent: true,
    });
    const plane = new THREE.Mesh( geometry, material );
    plane.position.set(x,y,0)
    plane.scale.set(size,size,1)
    return plane
}
export {model};